package bjtu.student.portrait.util;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.openapitools.jackson.nullable.JsonNullable;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.TIME})
public class NullableStringTypeHandler extends org.apache.ibatis.type.BaseTypeHandler<JsonNullable<String>> {

    @Override
    public JsonNullable<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return JsonNullable.of(rs.getString(columnName) == null ? null : rs.getString(columnName));
    }

    @Override
    public JsonNullable<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return JsonNullable.of(rs.getString(columnIndex) == null ? null : rs.getString(columnIndex));
    }

    @Override
    public JsonNullable<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return JsonNullable.of(cs.getString(columnIndex) == null ? null : cs.getString(columnIndex));
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JsonNullable<String> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.get());
    }
}
